package com.generic.mybatis.dal.dao.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 将string转为bool
 */
@MappedTypes(value = Boolean.class)
@MappedJdbcTypes(JdbcType.CHAR)
public class StringBooleanTypeHandler extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
            throws SQLException {
        String val = parameter == null || !parameter ? "n" : "y";
        ps.setString(i, val);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String val = rs.getString(columnName);
        return val != null && (val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes")||val.equalsIgnoreCase("1"));
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        String val = rs.getString(columnIndex);
        return val != null && (val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes")||val.equalsIgnoreCase("1"));
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String val = cs.getString(columnIndex);
        return val != null && (val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes")||val.equalsIgnoreCase("1"));
    }
}